const conn = require('../db/request')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const ctime = require('../util/time')
const config = require('../config/config')
//获取所有文章
exports.getArticle = async (req, res) => {
  const sql = `select * from articles `
  conn.query(sql, (err, results) => {
    if (err) {
      return res.cc('获取失败')
    }
    res.send({
      status: 0,
      results,
      message: '请求成功'
    })
  })
}
//获取文章列表
exports.getArticleList = (req, res) => {
  let { currentPage, pageSize } = req.body;
  if (!(currentPage && pageSize)) {
    res.cc('"参数错误!" ')
    return;
  }
  let sql = `select * from articles`;
  let total;
  conn.query(sql, (err, data) => {
    if (err) {
      return res.cc(err)
    }
    total = data.length;
    let n = (currentPage - 1) * pageSize;
    sql += ` order by ctime desc limit ${n}, ${pageSize}`;
    conn.query(sql, (err, data) => {
      if (err) {
        return res.cc(err)
      }
      res.send({
        total,
        data,
      });
    });
  });
};
//获取id文章
exports.getIdArticle = (req, res) => {
  const { id } = req.body
  const sql = `select * from articles where id=${id}`
  conn.query(sql, (err, results) => {
    if (err) {
      return res.cc('查询失败')
    }
    res.send({
      results,
      status: 0
    })
  })
}
//观看次数
exports.see = (req, res) => {
  const data = req.body
  console.log(`data.id`, data.id);
  console.log(`data.see`, data.see);
  console.log(data);

  let sees = data.see += 1
  console.log(`sees`, sees);
  const sql = `update articles set watch="${sees}" where id=${data.id}`
  conn.query(sql, (err, results) => {
    if (err) {
      return res.cc('执行失败')
    }
    res.send({
      results,
      sees
    })
  })
}
//点赞
exports.fabulous = (req, res) => {
  const data = req.body
  let Zan = data.fabulous += 1
  const sql = `update articles set fabulous="${Zan}" where id=${data.id}`
  conn.query(sql, (err, results) => {
    if (err)
      return res.cc('执行错误')
    res.send({
      results
    })
  })
}
//标签
exports.label = (req, res) => {
  let { currentPage, pageSize,label } = req.body;
  if (!(currentPage && pageSize&&label)) {
    res.cc('"参数错误!" ')
    return;
  }
  let sql = `select * from articles where label="${label}"`;
  let total;
  conn.query(sql, (err, data) => {
    if (err) {
      return res.cc(err)
    }
    total = data.length;
    let n = (currentPage - 1) * pageSize;
    sql += ` order by ctime desc limit ${n}, ${pageSize}`;
    conn.query(sql, (err, data) => {
      if (err) {
        return res.cc(err)
      }
      res.send({
        total,
        data,
      });
    });
  });
}
//注册
exports.register = (req, res) => {
  // 接收表单数据
  const userInfo = req.body
  // const ctime = ctime()

  const sql = `select * from UserWord where username=?`
  conn.query(sql, [userInfo.username], function (err, results) {
    // 执行 SQL 语句失败
    if (err) {
      return res.cc(err)
    }
    // 用户名被占用
    if (results.length > 0) {
      return res.cc('用户名被占用,请更换其他用户名!')
    }
    userInfo.password = bcrypt.hashSync(userInfo.password, 10)
    const sql = 'insert into UserWord set ?'
    conn.query(sql, { ctime:ctime(), username: userInfo.username, password: userInfo.password }, function (err, results) {
      // 执行 SQL 语句失败
      if (err) return res.cc(err)
      // SQL 语句执行成功，但影响行数不为 1
      if (results.affectedRows !== 1) {
        return res.cc('注册用户失败，请稍后再试！')
      }
      // 注册成功
      res.cc('注册成功！', 0)
    })
  })
}
// 登录
exports.login = (req, res) => {
  // 接收表单的数据
  const userInfo = req.body
  console.log(userInfo);
  // console.log('时间是',ctime());
  // const ctime = ctime()
  // console.log(ctime);
  // 定义 SQL 语句
  const sql = `select * from UserWord where username=?`
  // 执行 SQL 语句，根据用户名查询用户的信息
  conn.query(sql, userInfo.username, (err, results) => {
    // 执行 SQL 语句失败
    if (err) return res.cc(err)
    // 执行 SQL 语句成功，但是获取到的数据条数不等于 1
    if (results.length !== 1) return res.cc('登录失败！')

    // TODO：判断密码是否正确
    const compareResult = bcrypt.compareSync(userInfo.password, results[0].password)
    if (!compareResult) return res.cc('登录失败！')

    // TODO：在服务器端生成 Token 的字符串
    const user = { ...results[0], password: '', image: '' }
    // 对用户的信息进行加密，生成 Token 字符串
    // console.log(user);
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
    // 调用 res.send() 将 Token 响应给客户端
    res.send({
      status: 0,
      message: '登录成功！',
      token: 'Bearer ' + tokenStr,
      username:userInfo.username,
      results
    })
  })
}
//获取当前用户登录信息
exports.userInfo = (req, res) => {
  const { id } = req.body
  // console.log(userInfo.id);
  const sql = `select * from UserWord where id=${id}`
  conn.query(sql, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status:0,
      results
    })
  })
}